"""
 Title: CalendarTool.py
 Author: Matthew Tanner
 Project: Facultimes
 This is an Oregon State University project built as a requirement for CS419. 
 The project is a collaboration between Matthew Tanner, Arnold Baghomian, and
 Joseph Helgeson. 
 """

import requests
import json
from datetime import datetime
from xml.etree import ElementTree
import sys

class CalendarTool(object):
	"""Retrieves Google Calendar data and creates events.

	Uses Google API to retrieve all events from instructors' Google Calendars
	within a given time window. Converts Google data into event list with 
	each element of the form: [datetime, datetime, username]
	The event list is used by the Scheduler class to provide scheduling
	solutions.

    Attributes: 
    	TIME_FORMAT: Constant string for use in datetime conversion.
    	CONFIG_FILE_PATH: String constant for indicating path to config file.
    	Remaining attributes are meant to be private.
    """
	TIME_FORMAT = "%Y-%m-%dT%H:%M:%S-07:00"
	CONFIG_FILE_PATH = "facul-config.xml"

	def __init__(self):
		pass

	def events(self, schedulerObj, name, calendarId, start, end, api_key):
		"""Generates list of events

		Gets all calendar events from a given instructor's public Google
		calendar within a given time window. Converts data into Scheduler 
		events list.

		Args:
			Scheduler schedulerObj: schedulerObj is passed in so that
				error codes can be assigned to Scheduler.error.
			String name: username (instructor)
			String calendarId: A standard gmail email account.
			datetime start: start of given window
			datetime end: end of given window
			String api_key: Key required to make requests to the Google API.
		Returns:
			List of events: Each element as [datetime, datetime, username]
		"""
		startWindow = start.strftime(CalendarTool.TIME_FORMAT)
		endWindow = end.strftime(CalendarTool.TIME_FORMAT) 

		# build request url
		url = ('https://www.googleapis.com/calendar/v3/calendars/'
			+ calendarId + 
			'/events?'
			'singleEvents=true'
			'&timeMax=' + endWindow +
			'&timeMin=' + startWindow +
			'&key=' + api_key)
		
		# Make GET request to google calendar API for events
		try:
			r = requests.get(url).content
			j = json.loads(r)
		except requests.ConnectionError as err:
			schedulerObj.error = ("Network Error: Error connecting to Google API")
			return -1

		# check response for error
		if 'error' in j:
			error = j['error']['errors'][0]
			reason = error['reason']
			message = error['message']
			schedulerObj.error = ("Calendar error: '%s': '%s': %s" % (name, calendarId, reason))
			return -1

		# Build and return events list with datetime objects
		events = []
		for event in j['items']:
			string = event['start']['dateTime']
			start = datetime.strptime(string, CalendarTool.TIME_FORMAT)
			string = event['end']['dateTime']
			end = datetime.strptime(string, CalendarTool.TIME_FORMAT)
			events.append([start, end, name])
		if (events == None) or (events == []):
			return None
		return events

# Used for testing. Replace name value to test users google account as defined in 
# config file.
def main():
	name = "grimm, michael j"
	c = CalendarTool()
	events = c.events(name, datetime(2014, 7, 5, 07, 0), datetime(2014, 8, 25, 17, 0))
	if events == -1:
		print "error"
		sys.exit(1)
	for event in events:
		print event[0]
		print event[1]
		print
		
if __name__=='__main__':
	main()